<template>
   
  <div class="com_div com_div_pic">
    <div class="com_left">
      <div class="span">
        <span>{{ this.item_data.attrName }}</span>
      </div>
    </div>
    <div class="com_right">
      <div class="com_right_pic">
        <!-- 图片回显 -->
        <ul class="el-upload-list el-upload-list--picture-card">
          <li v-for="(earlyFile) in earlyFileList" :key="earlyFile.index" tabindex="0" class="el-upload-list__item is-success">
            <div>
              <img
                :src="earlyFile.url"
                alt=""
                class="el-upload-list__item-thumbnail"/>
              <span class="el-upload-list__item-actions" >
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(earlyFile)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span class="el-upload-list__item-delete" @click="handleDownload(earlyFile)">
                  <i class="el-icon-download"></i>
                </span>
                <span class="el-upload-list__item-delete" @click="handleRemoveEarly(earlyFile)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </li>
        </ul>
        <!-- 
              整理下思路：
              1、这是单文件上传，我选择了一个文件，她会展示在界面缩略图中，我点击手动上传，开始自动上传文件
              2、上传文件之前，执行 before-upload，获取到 oss服务 的签名，并保存
              3、真正的上传，action指定上传地址，data指定额外参数
              4、成功 or 失败，都会有对应的策略，成功：从 data 中获取到 图片 的路径
              5、修改 attrValue 的值，并修改 item_data 中 attrValue 的值
          :file-list="fileList"
          -->
        <el-upload
          class="com_upload_core"
          ref="upload"
          action="http://localhost:88/api/user/fileUpload"
          :headers="headers"
          list-type="picture-card"
          :auto-upload="false"
          :multiple="false"
          :limit="uploadMaxNum"
          :before-upload="beforeUpload"
          :before-remove="beforeRemove"
          :on-change="handleChange"
          :on-remove="handleRemove"
          :on-success="handleUploadSuccess"
          :on-preview="handlePreview"
          :on-exceed="hanlderExceed"
        >
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{ file }">
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
            <span class="el-upload-list__item-actions">
              <!-- 查看 -->
              <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <i class="el-icon-zoom-in"></i>
              </span>
              <!-- 下载 -->
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleDownload(file)"
              >
                <i class="el-icon-download"></i>
              </span>
              <!-- 删除 -->
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
          <!-- <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10MB</div> -->
        </el-upload>

        <!-- 这个 dialog 用于 在用户点击 已经上传的图片 时，进行图片的显示 -->
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>

        <!-- 控制按钮 -->
        <div class="btn_box">
          <el-button @click="doUpload">手动上传图片</el-button>
          <!-- <el-button @click="showPicDetail">显示图片信息</el-button> -->
          <!-- <el-button @click="test88">测试88</el-button> -->
          <!-- <el-button @click="showEarlyFL">获取earlyFL</el-button> -->
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  props: {
    item_data: Object,
  },
  computed: {
    allFileList() {
      // 展示的 图片列表
      return this.$refs.upload.uploadFiles;
    },
  },
  watch: {
    uploadNum: {
      handler: function (newValue) {
        if (newValue >= this.uploadMaxNum) {
          this.uploadDisplay("none");
        } else {
          this.uploadDisplay("");
        }
      },
    },
    item_data:{
      handler: function (newValue){
        this.init(newValue)
      }
    }

  },
  mounted() {
    this.init(this.item_data);
  },
  data() {
    return {
      uploadNum: 0,
      uploadMaxNum: 3,
      headers: {
        token: localStorage.getItem("user_token_" + this.currentUser.user.uid),
      },
      attrValue: "",
      earlyFileList: [],
      fileList: [], // 已成功上传的 图片列表【！！！重要！！！】
      // 下面 2 个，是有关图片放大的
      dialogVisible: false,
      dialogImageUrl: "",
      disabled: false, // 图片上除添加按钮外，其他两个按钮的现实
    };
  },
  methods: {
    // 生成 earlyFileList 用于回显图片
    init(item_data){
      this.$nextTick(() => { 
        this.attrValue = item_data.attrValue;
        this.earlyFileList = [];
        if (item_data.attrValue !== "") {
          var _arr = item_data.attrValue.split(";");
          for (var i = 0; i < _arr.length; i++) {
            this.earlyFileList.push({index: (i+1), name: "file" + i, url: _arr[i] });
          }
        }
        console.log("init获取earlyFL", this.earlyFileList)
        // this.earlyFileList = [
        //   {index: 1, name: 'file1', url:'https://fuss10.elemecdn.com/d/e6/c4d93a3805b3ce3f323f7974e6f78jpeg.jpeg'},
        //   {index: 2, name: 'file2', url:'https://fuss10.elemecdn.com/9/bb/e27858e973f5d7d3904835f46abbdjpeg.jpeg'},
        // ]
        this.uploadNum = this.earlyFileList.length; // 初始化 数量
      });
    },
    showEarlyFL(){
      console.log("earlyFL",this.earlyFileList)
    },
    // 测试：与 服务器的连通性
    test88() {
      this.$http1({
        url: this.$http.adornUrl("/user/file"),
        method: "post",
      }).then(({ data }) => {
        this.$message({
          type: "success",
          message: "成功!",
        });
        console.log("test88", data);
      });
    },
    // 测试：控制台打印 图片列表 信息
    showPicDetail() {
      console.log(
        "showPicDetail",
        this.fileList.length,
        this.fileList,
        this.allFileList
      );
    },
    // 测试：产生事件
    emitInput(val) {
      this.$emit("input", val);
    },
    // 上传图片
    doUpload() {
      console.log("手动上传图片");
      this.$refs.upload.submit();
    },

    // ===== 无关紧要的 事件处理函数 =====
    handleChange(file, fileList) {
      this.uploadNum = fileList.length + this.earlyFileList.length;
      console.log("onChange", file, fileList);
    },
    handleRemove(file, fileList) {
      console.log("onRemove", file, fileList);
      this.emitInput("");
    },
    handlePreview(file) {
      this.dialogVisible = true;
    },
    hanlderExceed(file, fileList) {
      console.log("onExceed", file, fileList);
    },

    beforeRemove(file, fileList) {
      console.log("beforeRemove", file, fileList);
    },
    beforeUpload(file) {
      console.log("beforeUpLoad", file);
    },

    // 上传图片后，保存信息到 “成功上传的图片列表”
    handleUploadSuccess(res, file, fileList) {
      console.log(
        "上传成功...",
        file,
        fileList,
        file.response.fileUrl,
        "成功 ",
        this.fileList
      );
      // console.log('success', );

      // 参数中的 fileList 不能动，他好像是跟 什么东西 挂钩的
      this.fileList.push({name: file.name, url: file.response.fileUrl})
      this.saveAttrValue() // 保存用户输入
    },

    // 保存 用户的输入【***重要***】
    saveAttrValue() {
      var attrValue = "";
      let _FL = this.fileList;
      let _earlyFL = this.earlyFileList;
      for(var i = 0; i < _earlyFL.length ; i++){
        if(i === _earlyFL.length-1){
          attrValue += _earlyFL[i].url
        }else{
          attrValue += _earlyFL[i].url + ';'
        }
      }
      if(attrValue !== '' && _FL.length > 0){
        attrValue += ';'
      }
      for (var i = 0; i < _FL.length; i++) {
        if (i === 0) {
          attrValue += _FL[i].url;
        } else {
          attrValue += ";" + _FL[i].url;
        }
      }
      this.attrValue = attrValue; // 中间temp变量
      this.item_data.attrValue = attrValue; // 保存用户输入
      // this.item_data.
    },
    // 当图片列表中个数 达到3个，display:none, 正常情况下，display:
    uploadDisplay(display) {
      var upload = this.$refs.upload;
      // console.log("upload", upload, upload.$children[1])
      upload.$children[1].$el.style.display = display;
    },

    // ===== 对图片列表中图片的一些操作 =====
    // 删除图片
    handleRemove(file) {
      var index = this.getFileListIndex(file, this.allFileList);
      if (index != -1) {
        this.allFileList.splice(index, 1);
        console.log("成功删除这个图片", file, file.response);
        if (typeof file.response !== "undefined") {
          this.updateFileList();
        }
      }
      this.uploadNum--;
    },
    // 更新成功上传的图片列表
    updateFileList() {
      let temp = [];
      for (var i = 0; i < this.allFileList.length; i++) {
        if (typeof this.allFileList[i].response !== "undefined") {
          temp.push({
            name: this.allFileList[i].name,
            url: this.allFileList[i].response.fileUrl,
          });
        }
      }
      this.fileList = temp;
      console.log("updateFileList", this.fileList, this.allFileList);
    },
    // 删除 early之前 的 图片
    handleRemoveEarly(file){
      var index = this.getEarlyFileListIndex(file)
      if(index !== -1){
        this.earlyFileList.splice(index, 1)
        this.uploadNum --;
      }
      this.saveAttrValue();
    },
    // 展示图片大图
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 控制台打印图片信息
    handleDownload(file) {
      console.log("下载这个图片", file);
    },
    // 获取图片列表中某个图片的下标
    getFileListIndex(file, fileList) {
      for (var i = 0; i < fileList.length; i++) {
        if (file.uid === fileList[i].uid) {
          return i;
        }
      }
      return -1;
    },
    // 获取 early图片列表 中 某个图片的下标
    getEarlyFileListIndex(file){
      var _earlyFL = this.earlyFileList;
      for(var i = 0;i<_earlyFL.length;i++){
        if(file.index === _earlyFL[i].index){
          return i;
        }
      }
      return -1;
    }
  },
};
</script>
<style>
.com_div_pic {
  height: 160px;
}
.com_right_pic{
  margin-top: 5px;
}
.com_upload_core{
  display: inline-block;
}

.com_right .btn_box{
  display: flex;
}
</style>


